package it.trekker.converter;

import java.io.FileReader;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.Date;
import it.trekker.upload.json.ExcursionAdapter;
import com.google.gson.*;

public class JsonConverter implements IJsonConverter {

	private static final String DATE_FORMAT = "EEE, dd MMM yyyy HH:mm:ss zzz";
//	private static final String DATE_FORMAT = "dd MMM yyyy HH:mm:ss";
	private Gson gson;

	public JsonConverter() {
		gson = new GsonBuilder().registerTypeAdapter(Date.class, new DateTypeAdapter()).create();
//		gson = new GsonBuilder().setDateFormat(DATE_FORMAT).create();
//		gson = new Gson();
	}

	public String ExcursionAdapter2Json(ExcursionAdapter excursion) {
		return gson.toJson(excursion);
	}

	public ExcursionAdapter Json2ExcursionAdapter(String json) {
		return gson.fromJson(json, ExcursionAdapter.class);
	}

	public String ExcursionAdapterArray2Json(ExcursionAdapter[] excursions) {
		return gson.toJson(excursions);
	}

	public ExcursionAdapter[] Json2ExcursionAdapterArray(String json) {
		return gson.fromJson(json, ExcursionAdapter[].class);
	}

	public ExcursionAdapter[] JsonFile2ExcursionAdapterArray(FileReader reader) {
		return gson.fromJson(reader, ExcursionAdapter[].class);
	}



	public class DateTypeAdapter implements JsonSerializer<Date>, JsonDeserializer<Date> {

//		private final DateFormat format = DateFormat.getInstance();
		private final SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT);

		public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {
//			String dateFormatAsString = format.format(src);
			String dateFormatAsString = String.valueOf(src.getTime());
			return new JsonPrimitive(dateFormatAsString);
		}

		public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
			if (!(json instanceof JsonPrimitive)) {
				throw new JsonParseException("The date should be a string value");
			}

//			try {
//				return format.parse(json.getAsString());
//			} catch (ParseException e) {
//				throw new JsonParseException(e);
//			}
			return new Date(json.getAsLong());
		}
	}
}
